package com.sinven.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sinven.common.ActionResult;
import com.sinven.common.Pager;
import com.sinven.pojo.Classification;
import com.sinven.pojo.Content;
import com.sinven.pojo.User;
import com.sinven.serivce.ClassificationSerivce;
import com.sinven.serivce.CommentSerivce;
import com.sinven.serivce.ContentSerivce;
import com.sinven.serivce.UserSerivce;
import com.sinven.vo.UploadResult;

@Controller
public class PersonalController {

	/**
	 * 创建用户Serivce层对象
	 */
	@Autowired
	private UserSerivce serivce;

	/**
	 * 创建分类Serivce层对象
	 */
	@Autowired
	private ClassificationSerivce classifi;

	/**
	 * 创建内容Serivce层对象
	 */
	@Autowired
	private ContentSerivce content;

	
	/**
	 * 创建评论的Serivce层对象
	 */
	@Autowired
	private CommentSerivce commentService;
	
	/**
	 * 跳入登陆页面
	 * @return
	 */
	@RequestMapping("login.html")
	public String loginhtml() {
		return "front/login";
	}

	/**
	 * 跳入注册页面
	 * @return
	 */
	@RequestMapping("registe")
	public String registe() {
		return "front/registe";
	}

	/**
	 * 判断登录名是否存在
	 * @param userCode
	 * @return
	 */
	@RequestMapping("queryByUserCode")
	@ResponseBody
	public Boolean queryByUserCode(String userCode) {
		return serivce.queryByUserCodez(userCode);
	}

	/**
	 * 判断用户名是否存在
	 * @param userName
	 * @return
	 */
	@RequestMapping("queryByUserName")
	@ResponseBody
	public Boolean queryByUserName(String userName) {
		return serivce.queryByUserName(userName);
	}

	/**
	 * 添加用户
	 * @param user
	 * @return
	 */
	@RequestMapping("addUser")
	@ResponseBody
	public Boolean addUser(User user) {
		return serivce.addUser(user);
	}

	/**
	 * 登录
	 * 
	 * @param userCode
	 * @param password
	 * @param session
	 * @return
	 */
	@RequestMapping("login")
	@ResponseBody
	public boolean login(String userCode, String password, HttpSession session) {
		//调用user的serivce层 
		User user = serivce.queryByUserCode(userCode, password);
		if (user == null) {//如果user为null
			return false;//返回false
		}
		//否则将user传入到session的userz中
		session.setAttribute("userz", user);
		//返回true
		return true;
	}

	/**
	 * 退出
	 */
	@RequestMapping("tuichu")
	public String tuichu(HttpSession session) {
		//将session里面的userz设置值为null
		session.setAttribute("userz", null);
		//重定向跳转index请求
		return "redirect:index";
	}

	/**
	 * 进入后台页面的请求
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("indexs")
	public String backmain(Model model, HttpSession session) {
		//获取用户的user对象
		User user = (User) session.getAttribute("userz");
		//查询所有栏目
		List<Classification> classlist = classifi.queryAll();
		//装入model
		model.addAttribute("fenlei", classlist);
		//创建一个list对象
		List<Long> countlist = new ArrayList<Long>();
		for (Long i = (long) 1; i <= classlist.size(); i++) {
			//查询每个栏目发布文章数
			countlist.add(content.countContent(i, (long) user.getUid()));
		}
		//装入model
		model.addAttribute("countlist", countlist);
		//返回到后台页面
		return "front/Personal";
	}

	/**
	 * 根据类型的文章分页查询
	 * 
	 * @param curPage
	 * @param pageSize
	 * @param cid
	 * @return
	 */
	@RequestMapping("table")
	@ResponseBody
	public ActionResult<List<Content>> tableDemo(@RequestParam(value = "page", defaultValue = "0") Long curPage,
			@RequestParam(value = "limit", defaultValue = "10") Integer pageSize, Long cid, HttpSession session) {
		//获取session里面的user对象
		User user = (User) session.getAttribute("userz");
		//第一个值当前页 第二个值每页显示数 第三个值 栏目id 第四个值 用户id
		Pager<List<Content>> pager = content.queryPaging(curPage, pageSize, cid,user.getUid());
		//创建ActionResult对象
		ActionResult<List<Content>> result = new ActionResult<>();
		//设置参数
		result.setCode(0);
		if (pager == null) {//如果pager为空
			result.setData(null);//设置参数
			result.setCount(0L);//设置参数
		} else {
			result.setCount(pager.getTotalRecords());//设置参数
			result.setData(pager.getData());//设置参数
		}
		//返回 result
		return result;
	}

	/**
	 * 添加文章
	 * 
	 * @param contentz
	 * @return
	 */
	@RequestMapping("addContent")
	@ResponseBody
	public Boolean addContent(Content contentz) {
		return content.addContent(contentz);
	}

	/**
	 * 查询一条文章的详细信息
	 * 
	 * @param tid
	 * @return
	 */
	@PostMapping("queryBytid/{tid}")
	@ResponseBody
	public Content ContentBytid(@PathVariable("tid") Long tid, Model model) {
		try {
			//根据内容id查询一条内容的详细数据
			Content contenz = content.queryBytid(tid);
			//装入model
			model.addAttribute("content", contenz);
			//返回数据
			return contenz;
		} catch (Exception e) {
			e.printStackTrace();
			//返回null
			return null;
		}
	}

	/**
	 * 修改内容
	 * 
	 * @param contentz
	 * @return
	 */
	@PostMapping("updateContent")
	@ResponseBody
	public Boolean updateContentone(Content contentz) {
		return content.updateContent(contentz);
	}

	/**
	 * 修改用户
	 * 
	 * @param user
	 * @return
	 */
	@PostMapping("updateUser")
	@ResponseBody
	public Boolean updateUserone(User users, HttpSession session) {
		//修改用户
		boolean result = serivce.updateUser(users);
		//重新查询user
		User user = serivce.queryByUserCode(users.getUserCode(), users.getPassword());
		//装入到userz中
		session.setAttribute("userz", user);
		//返回 true或false
		return result;
	}

	/**
	 * 删除内容
	 * 
	 * @param tid
	 * @return
	 */
	@DeleteMapping("deleteContent/{tid}")
	@ResponseBody
	public Boolean deleteContentone(@PathVariable("tid") Long tid) {
		//根据内容id删除所有评论
		boolean result1=commentService.deleteComment(tid);
		//根据内容id删除内容
		boolean result2=content.deleteContent(tid);
		//如果两个都为true
		if(result1==true && result2==true) {
			//返回 true
			return result1;
		}
		if(result1==false) {//如果result1为false
			return result1;//返回false
		}
		if(result2==false) {//如果result2位false
			return result2;//返回false
		}
		return result2;//返回根据内容id删除的结果s
	}

	/**
	 * 上传图片的请求
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	@RequestMapping("upload")
	@ResponseBody
	public UploadResult upload(MultipartFile file, HttpServletRequest request) {
		String name = request.getServletContext().getContextPath();
		UploadResult result = new UploadResult();
		// 目录打散 以日期打散
		String firstPath = Calendar.getInstance().get(Calendar.YEAR) + "";
		String secondPath = Calendar.getInstance().get(Calendar.MONTH) + 1 + "";
		// 得到文件原文件名
		String oldFileName = file.getOriginalFilename();
		// 得到后缀
		String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
		// 生成新文件名
		String newFileName = UUID.randomUUID().toString() + suffix;
		// 生成目标文件
		File dest = new File("D:\\upload" + File.separator + firstPath + File.separator + secondPath, newFileName);
		// 生成文件夹
		if (!dest.exists()) {
			dest.mkdirs();
		}
		// 将上传文件保存到服务器目录
		try {
			file.transferTo(dest);
			result.setErrno(0);
			List<String> data = new ArrayList<String>();
			String relativeFilename = name + "/upload/" + firstPath + "/" + secondPath + "/" + newFileName;
			data.add(relativeFilename);
			result.setData(data);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
			result.setErrno(1);
		}
		return result;
	}
}
